package behaviorPattern.memento;

/**
 * @Author: Alex Hu
 * Date: 2020/2/22 2:47 下午
 * Content:
 */
public class PrototypeMemento {
    public static void main(String[] args) {
        OriginatorPrototype or = new OriginatorPrototype();
        PrototypeCaretaker cr = new PrototypeCaretaker();
        or.setState("S0");
        System.out.println("初始状态:" + or.getState());
        /**保存状态*/
        cr.setMemento(or.createMemento());
        or.setState("S1");
        System.out.println("新的状态:" + or.getState());
        /**恢复状态*/
        or.restoreMemento(cr.getMemento());
        System.out.println("恢复状态:" + or.getState());
    }
}

/**
 * 发起人原型
 */
class OriginatorPrototype implements Cloneable {
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public OriginatorPrototype createMemento() {
        return this.clone();
    }

    public void restoreMemento(OriginatorPrototype opt) {
        this.setState(opt.getState());
    }

    @Override
    public OriginatorPrototype clone() {
        try {
            return (OriginatorPrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

/**
 * 原型管理者
 */
class PrototypeCaretaker {
    private OriginatorPrototype opt;

    public OriginatorPrototype getMemento() {
        return opt;
    }

    public void setMemento(OriginatorPrototype opt) {
        this.opt = opt;
    }
}
